﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml;
using System.IO.IsolatedStorage;
using System.IO;
using System.ServiceModel.Syndication;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace JakartaGuide
{
    public partial class MainPage : PhoneApplicationPage
    {
        public List<Article> Articles;
        private ProgressIndicator downloadIndicator;
        private const String localFile = "tribunjakarta.rss";

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            downloadIndicator = new ProgressIndicator() { IsVisible = false, IsIndeterminate = true, Text = "Fetching feed..." };
            SystemTray.SetProgressIndicator(this, downloadIndicator);
        }

        private void ReadLocalFeed_Click(object sender, EventArgs e)
        {
            ReadLocalFeed();
        }

        private void ReadLocalFeed()
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, args) =>
            {
                using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
                using (IsolatedStorageFileStream stream = userStore.OpenFile(localFile, FileMode.Open))
                using (StreamReader reader = new StreamReader(stream)) {
                    var original = reader.ReadToEnd();
                    // Hacks to make TribunNews RSS feed work
                    var doc = original.Replace("&acirc;", "&#226;");

                    using (var docReader = new StringReader(doc))
                    using (XmlReader xmlReader = XmlReader.Create(docReader))
                    {
                        SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
                        var titles = new List<String>();
                        var articles = feed.Items.Select((item) =>
                        {
                            var article = new Article();
                            article.Title = item.Title.Text;
                            article.Summary = Regex.Replace(item.Summary.Text, "<[^>]+>", "");
                            article.Uri = item.Links.First(x => x.RelationshipType != "enclosure").Uri;
                            try
                            {
                                article.ImageUri = item.Links.First(x => x.RelationshipType == "enclosure").Uri;
                                article.ThumbnailSource = article.ImageUri.ToString();
                            }
                            catch (Exception)
                            {
                                article.ThumbnailSource = "/JakartaGuide;component/Images/detik-logo_trans.png";
                            }
                            article.PublishDate = item.PublishDate;
                            article.Publisher = "Tribun Jakarta";
                            return article;
                        });
                        args.Result = articles;
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                listBox1.Items.Clear();
                var articles = (IEnumerable<Article>)e.Result;
                foreach (var article in articles)
                    listBox1.Items.Add(article);
            };
            worker.RunWorkerAsync();
        }

        /**
         * Debugging purpose.
         */
        private void ShowLocalContent()
        {
            using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream stream = userStore.OpenFile(localFile, FileMode.Open))
            using (StreamReader reader = new StreamReader(stream))
            {
                var content = reader.ReadToEnd();
                MessageBox.Show(content);
            }
        }

        private void DownloadFeed()
        {
            var feedUrl = "http://jakarta.tribunnews.com/rss";

            downloadIndicator.Text = "Fetching " + feedUrl + " ...";
            downloadIndicator.IsVisible = true;

            var feedUri = new Uri(feedUrl);
            var downloader = new WebClient();
            downloader.AllowReadStreamBuffering = true;
            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
            downloader.OpenReadAsync(feedUri);
        }

        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            downloadIndicator.IsVisible = false;

            if (e.Error is Exception)
            {
                MessageBox.Show(e.Error.ToString(), "Error during download", MessageBoxButton.OK);
                return;
            }
            else if (e.Cancelled)
            {
                return;
            }

            using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream stream = userStore.CreateFile(localFile))
            {
                e.Result.CopyTo(stream);
            }

            //MessageBox.Show("Saved to " + localFile);
            ReadLocalFeed();
            
            //var xmlReader = XmlReader.Create(e.Result);
            //var feedContent = xmlReader.ReadInnerXml();
            //MessageBox.Show(feedContent);
        }

        //private void FillListBox1_Click(object sender, EventArgs e)
        //{
        //    listBox1.Items.Clear();
        //    listBox1.Items.Add("Hendy");
        //    listBox1.Items.Add("Baim");
        //}

        private void ReadLocalFeedOrRefresh()
        {
            using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (userStore.FileExists(localFile))
                {
                    ReadLocalFeed();
                }
                else
                {
                    DownloadFeed();
                }
            }
        }

        private void ArticleList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var article = listBox1.SelectedItem as Article;
            //MessageBox.Show(article.ToString() + article.Url);
            var browser = new WebBrowserTask();
            browser.Uri = article.Uri;
            browser.Show();
        }

        private void mainPage_Loaded(object sender, RoutedEventArgs e)
        {
            ReadLocalFeedOrRefresh();
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            DownloadFeed();
        }

        private void About_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Jakarta Guide versi 1.0.0\r\n" +
                "\u00a9 2012 Hendy Irawan.\r\n" +
                "Licensed under GNU General Public License (GPL) version 2.0.\r\n" +
                "http://jakartaguide.codeplex.com/\r\n\r\n" +
                "Logo 'Enjoy Jakarta' by Dinas Pariwisata DKI Jakarta. " +
                "Konten disarikan dari Tribun Jakarta \u00a9 TRIBUNnews.com.",
                "Tentang Jakarta Guide", MessageBoxButton.OK);
        }
    }
}